package com.fatcat.easybuy.service.impl;

import com.fatcat.easybuy.exception.BusinessException;
import com.fatcat.easybuy.pojo.EasyBuyShoppingCart;
import com.fatcat.easybuy.service.EasyBuyShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.BoundListOperations;
import org.springframework.data.redis.core.BoundZSetOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author 郝秦毅
 * @since 2025/9/19 15:50
 */
@Service
public class EasyBuyShoppingCartServiceImpl implements EasyBuyShoppingCartService {
    private final String SHOPPING_CART_HASH = "shoppingCartHash:";
    private final String SHOPPING_CART_ZSET = "shoppingCartzSet:";
    private final String SHOPPING_CART_LIST = "shoppingCartList:";
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询购物车列表
     */
    @Override
    public List<EasyBuyShoppingCart> getShoppingCartList(Long userId) {
//        BoundZSetOperations<String, Long> zSetOps = redisTemplate.boundZSetOps(SHOPPING_CART_ZSET + userId);
//        Set<Long> cartSet = zSetOps.reverseRange(0, -1);
//        if (cartSet == null || cartSet.isEmpty()) {
//            return new ArrayList<>();
//        }
//        List<String> keyList = new ArrayList<>();
//        for (Long key : cartSet) {
//            keyList.add(String.valueOf(key));
//        }
        BoundHashOperations<String, String, EasyBuyShoppingCart> hashOps = redisTemplate.boundHashOps(SHOPPING_CART_HASH + userId);

        return new ArrayList<>(hashOps.values());
    }

    /**
     * 添加购物车商品
     */
    @Override
    public boolean addProductToCart(Long userId, EasyBuyShoppingCart easyBuyShoppingCart) {
//        long now = System.currentTimeMillis();
//        easyBuyShoppingCart.setScore(now);
//        // Zset有序序列保存购物车添加顺序（时间戳）
//        BoundZSetOperations<String, Long> zSetOps = redisTemplate.boundZSetOps(SHOPPING_CART_ZSET + userId);
//        Long productId = easyBuyShoppingCart.getProductId();
//
//        // 更新时间戳
//        zSetOps.add(productId, now);
//
        // Hash保存商品详细信息
        BoundHashOperations<String, String, EasyBuyShoppingCart> hashOps = redisTemplate.boundHashOps(SHOPPING_CART_HASH + userId);
        String productIdStr = easyBuyShoppingCart.getProductId().toString();

        if (hashOps.hasKey(productIdStr)) {
            // 商品已存在，累加数量
            EasyBuyShoppingCart exitCart = hashOps.get(productIdStr);
            exitCart.setQuantity(exitCart.getQuantity() + easyBuyShoppingCart.getQuantity());

            // 更新时间戳为当前最新
//            exitCart.setScore(now);

            hashOps.put(productIdStr, exitCart);
        } else {
            // 商品不存在，直接添加
            hashOps.put(productIdStr, easyBuyShoppingCart);
        }

        // 验证ZSet中存在该商品且score正确，同时Hash中存在该商品
//        boolean zSetSuccess = zSetOps.score(productId) != null && zSetOps.score(productId).longValue() == now;

        boolean hashSuccess = hashOps.hasKey(productIdStr);
        return hashSuccess;
    }

    /**
     * 删除购物车商品
     */
    @Override
    public boolean deleteProductFromCart(Long userId, Long productId) {
        //Zset有序序列保存购物车添加顺序（时间戳）
//        BoundZSetOperations<String, Long> zSetOps = redisTemplate.boundZSetOps(SHOPPING_CART_ZSET + userId);
//        boolean zSetBool = zSetOps.remove(productId) > 0;
        //hash删除
        boolean hashBool = false;
        BoundHashOperations<String, String, EasyBuyShoppingCart> hashOps = redisTemplate.boundHashOps(SHOPPING_CART_HASH + userId);
        if (hashOps.hasKey(productId.toString())) {
            hashBool = hashOps.delete(productId.toString()) > 0;
        }
        return hashBool;
    }

    /**
     * 修改购物车商品
     */
    @Override
    public boolean updateProductInCart(Long userId, EasyBuyShoppingCart cartItem) {
        // 参数校验
        if (userId == null || cartItem == null || cartItem.getProductId() == null) {
            throw new BusinessException("参数不能为空");
        }
        // 校验商品数量quantity是购买数量必须大于0
        Integer quantity = cartItem.getQuantity();
        if (quantity == null || quantity <= 0) {
            throw new BusinessException("商品数量必须大于0");
        }

        long now = System.currentTimeMillis();
        //更新score
//        BoundZSetOperations<String, Long> zSetOps = redisTemplate.boundZSetOps(SHOPPING_CART_ZSET + userId);
        BoundHashOperations<String, String, EasyBuyShoppingCart> hashOps = redisTemplate.boundHashOps(SHOPPING_CART_HASH + userId);
        String productIdStr = cartItem.getProductId().toString();
        if (!hashOps.hasKey(productIdStr)) {
            throw new BusinessException("购物车中不存在该商品，无法更新");
        }
//        zSetOps.add(cartItem.getProductId(), now); // 直接设置最新时间戳为分数

        // 更新Hash
        hashOps.put(productIdStr, cartItem);

        EasyBuyShoppingCart updatedItem = hashOps.get(productIdStr);
        return updatedItem != null && quantity.equals(updatedItem.getQuantity());
    }

    /**
     * 清空购物车
     */
    @Override
    public boolean clearShoppingCart(Long userId) {
//        boolean zSetBool = redisTemplate.delete(SHOPPING_CART_ZSET + userId);
        return redisTemplate.delete(SHOPPING_CART_HASH + userId);
    }
}
